/**
 * @Author: jipeng.Li
 * @Date: 2021-04-21 08:21:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-21 08:21:21
 * @Description: 核销详情
 */

import React, { Component } from 'react';
import {
  BackHandler,
  Image,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  DeviceEventEmitter
} from 'react-native';
import {
  Button,
  DashLine,
  msg,
  XMHeader,
  BackImage
} from '@/common';
import {
  fontColorBlack,
  isAndroid,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp
} from '@/styles';
import {
  iconSuccessGreen,
  writeOffDetailsRefund
} from '@/images';
import tool from '@/common/getDate';
import oil from '@/api/oil';

const { Submit } = Button;

export default class WriteOffDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      writeOffState: 0,
      writeOffAmount: 0,
      userDetails: {},
      oilDetails: {},
      refundDetails: {},
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { pumpOilNo } = params;
    this.getVerificationDetail(pumpOilNo);
    if (isAndroid) {
      BackHandler.addEventListener('hardwareBackPress', this.androidBack);
    }
  }

  componentWillUnmount() {
    if (isAndroid) {
      BackHandler.removeEventListener('hardwareBackPress', this.androidBack);
    }
  }

  writeOffState = {
    0: {
      icon: writeOffDetailsRefund,
      text: '未核销',
      subText: '未核销金额'
    },
    1: {
      icon: iconSuccessGreen,
      text: '已核销',
      subText: '核销金额'
    },
    2: {
      icon: writeOffDetailsRefund,
      text: '已退款',
      subText: '退款金额'
    }
  }

  render() {
    const { userDetails, oilDetails, refundDetails, writeOffState, writeOffAmount } = this.state;
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: mainBgColorLightGray }}>
        {this._renderHead()}
        <View style={styles.cardView}>
          <View style={styles.headBrand}>
            <View style={styles.brandTextTips}>
              <Image
                source={this.writeOffState[writeOffState].icon}
                style={{
                  width: px2dp(50),
                  height: px2dp(50),
                  marginRight: px2dp(16)
                }}
              />
              <Text style={styles.brandText}>{this.writeOffState[writeOffState].text}</Text>
            </View>
            <Text style={styles.brandText}>
              ¥
              <Text style={{ fontSize: px2dp(64) }}>{writeOffAmount}</Text>
            </Text>
            <Text style={{ color: '#999793', fontSize: px2dp(26) }}>{this.writeOffState[writeOffState].subText}</Text>
          </View>
          <View style={styles.details}>
            {
              Object.keys(oilDetails).map((value, index) => {
                return (
                  <View key={`oilDetailsLine${index}`} style={styles.detailsLine}>
                    <Text style={styles.lineText}>{`${value}`}</Text>
                    <Text style={styles.lineTextValue}>{oilDetails[value]}</Text>
                  </View>
                );
              })
            }
          </View>
          <View style={styles.details}>
            <DashLine />
            {
              Object.keys(userDetails).map((value, index) => {
                return (
                  <View key={`userDetailsLine${index}`} style={styles.detailsLine}>
                    <Text style={styles.lineText}>{`${value}`}</Text>
                    <Text style={styles.lineTextValue}>{userDetails[value]}</Text>
                  </View>
                );
              })
            }
          </View>
          {
            writeOffState === 2 && (
              <View style={styles.details}>
                <DashLine />
                {
                  Object.keys(refundDetails).map((value, index) => {
                    return (
                      <View key={`userDetailsLine${index}`} style={styles.detailsLine}>
                        <Text style={styles.lineText}>{`${value}`}</Text>
                        <Text style={styles.lineTextValue}>{refundDetails[value]}</Text>
                      </View>
                    );
                  })
                }
              </View>
            )
          }
        </View>
      </SafeAreaView>
    );
  }

  _renderHead = () => {
    return (
      <XMHeader
        renderLeft={() => (
          <TouchableOpacity
            activeOpacity={0.8}
            onPress={this.goBack}
            style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
              { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
          >
            <BackImage />
          </TouchableOpacity>
        )}
        renderTitle={() => <Text style={{ color: '#333232', fontWeight: 'bold', fontSize: px2dp(36) }}>核销结果</Text>}
      />
    );
  }

  goBack = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { backRouteName } = params;
    if (backRouteName === 'OilCardPlatform') {
      DeviceEventEmitter.emit('reloadList');
    }

    msg.emit('router: goToNext', {
      routeName: backRouteName,
    });
  };

  androidBack = () => {
    this.goBack();
    return true;
  }

  getVerificationDetail = (pumpOilNo) => {
    oil.getVerificationDetail({ pumpOilNo }).then(res => {
      if (res.success) {
        const {
          legalName,
          carownerName,
          oil,
          writeOffAmountPer,
          writeOffAmount,
          gunNo,
          carNo,
          oilCount,
          carNoNew,
          driverName,
          driverMobile,
          oilTime,
          writeOffStatus,
          carownerMobile,
          writeOffTime,
          refundReason,
          refundTime
        } = res.data;
        let userDetails = {
          法人名称: legalName,
          车主名称: `${carownerName} ${carownerMobile}`,
          司机名称: `${driverName || ''} ${driverMobile || ''}`,
          备注车牌: carNoNew
        };

        let oilDetails = {
          油品: `${oil}#`,
          单价: `${writeOffAmountPer}元 / 升`,
          加油升数: `${oilCount}升`,
          加油枪号: `${gunNo}号`,
          车牌号码: carNo || '',
          加油时间: oilTime ? tool.dateForm(oilTime, 'yyyy.MM.dd hh:mm:ss') : '',
          核销时间: writeOffTime ? tool.dateForm(writeOffTime, 'yyyy.MM.dd hh:mm:ss') : '',
        };

        let refundDetails = {
          退款时间: refundTime ? tool.dateForm(refundTime, 'yyyy.MM.dd hh:mm:ss') : '',
          退款理由: refundReason || '',
        };

        this.setState({ userDetails, oilDetails, refundDetails, writeOffAmount, writeOffState: writeOffStatus });
      } else {
        msg.emit('app:tip', { text: res.msg });
        msg.emit('router: back');
      }
    });
  }
}

const styles = StyleSheet.create({
  cardView: {
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(16),
    padding: px2dp(24),
    margin: px2dp(32)
  },
  headBrand: {
    height: px2dp(200),
    alignItems: 'center',
    justifyContent: 'space-around',
    marginBottom: px2dp(64)
  },
  brandTextTips: {
    flexDirection: 'row'
  },
  brandText: {
    fontSize: px2dp(40),
    fontWeight: 'bold'
  },
  details: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(24)
  },
  detailsLine: {
    flexDirection: 'row',
    height: px2dp(26 + 32),
  },
  lineText: {
    fontSize: px2dp(26),
    color: '#999793',
    lineHeight: px2dp(26 + 32),
  },
  lineTextValue: {
    flex: 1,
    fontSize: px2dp(26),
    color: fontColorBlack,
    lineHeight: px2dp(26 + 32),
    textAlign: 'right',
  },
  btnBoxStyle: {
    height: px2dp(80),
    borderRadius: px2dp(10),
    width: '80%',
    marginTop: px2dp(30),
  },
  tipsText: {
    color: '#999793',
    fontSize: px2dp(22)
  },
});
